package logic

import (
	"context"
	"fmt"
	"manage/models/redis"
	"manage/pkg"
	"strconv"
	"time"

	"math/rand"

	"manage/managerpc/internal/svc"
	"manage/managerpc/managerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信
func (l *SendSmsLogic) SendSms(in *managerpc.SendSmsRequest) (*managerpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	code := rand.Intn(9000) + 1000
	get := redis.Rdb.Get(l.ctx, "sendsmsTime"+in.Account)
	if get.Val() >= "1" {
		return nil, fmt.Errorf("一分钟内只能发送一次")
	}
	sms, err := pkg.SendSms(in.Account, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	redis.Rdb.Set(l.ctx, "sendsms"+in.Account, code, time.Minute*3)
	redis.Rdb.Incr(l.ctx, "sendsmsTime"+in.Account)
	redis.Rdb.Expire(l.ctx, "sendsmsTime"+in.Account, time.Minute)
	return &managerpc.SendSmsResponse{}, nil
}
